package com.dz.lm.common.util;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version 1.8;
 * @author: LDY;
 * @Description;
 * @Date: Created in 2020/3/21 14:22;
 */
public class StringUtil {
    /**
     * 空字符判断
     *
     * @param strs
     * @return
     */
    public static boolean containEmpty(String... strs) {
        for (String str : strs) {
            if (str == null || "".equals(str.trim())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否数字判断
     *
     * @param strs
     * @return
     */
    public static boolean isNumber(String... strs) {
        for (String str : strs) {
            if (str == null || "".equals(str)) {
                return false;
            } else if (!str.matches("\\d+")) {
                return false;
            }
        }
        return true;
    }

    /**
     * 字符加密
     * @param key
     * @return
     */
    public static String getURLEncoderOld(String key){
        if(!com.smartlbs.util.StringUtil.containEmpty(key)){
            return URLEncoder.encode(URLEncoder.encode(key));
        }
        return "";
    }
    public static boolean getBool(Object obj, boolean def){
        if (obj != null) {
            try {
                return Boolean.valueOf(obj.toString());
            } catch (NumberFormatException e) {
                return def;
            }
        }
        return def;
    }
    /**
     * 返回字符串的int形式
     *
     * @param str
     *            待转换字符串
     * @param def
     *            无法转换时默认返回值
     * @return
     */
    public static int getInt(Object str, int def) {
        if (str == null) {
            return def;
        }
        return getInt(str.toString(), def);
    }
    public static int getInt(String str, int def) {
        if (str == null) {
            return def;
        }
        int result = def;
        try {
            result = Integer.valueOf(str.toString());
        } catch (NumberFormatException e) {
            return def;
        }
        return result;
    }
    public static String getString(Object obj){
        if(obj == null){
            return "";
        }
        return obj.toString();
    }
    /**
     * 判断字符串是否是整数
     */
    public static boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断是否是大于0的整数
     */
    public static boolean isGqInteger(String value) {
        try {
            int i = Integer.parseInt(value);
            if(i>0){
                return true;
            }else{
                return false;
            }
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断字符串是否是浮点数
     */
    public static boolean isDouble(String value) {
        try {
            Double.parseDouble(value);
            if (value.contains("."))
                return true;
            return false;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断字符串是否是数字
     */
    public static boolean isNumber(String value) {
        return isInteger(value) || isDouble(value);
    }

    /**
     * 返回字符串的long形式
     *
     * @param str
     *            待转换字符串
     * @param def
     *            无法转换时默认返回值
     * @return
     */
    public static long getLong(Object str, long def) {
        if (str == null) {
            return def;
        }
        return getLong(str.toString(), def);
    }
    public static long getLong(String str, long def) {
        if (str == null) {
            return def;
        }
        long result = def;
        try {
            result = Long.valueOf(str.toString());
        } catch (NumberFormatException e) {
            return def;
        }
        return result;
    }
    /**
     * 返回字符串的double形式
     *
     * @param str
     *            待转换字符串
     * @param def
     *            无法转换时默认返回值
     * @return
     */
    public static double getDouble(Object str, double def) {
        if (str == null) {
            return def;
        }
        return getDouble(str.toString(), def);
    }

    public static double getDouble(String str, double def) {
        if (str == null) {
            return def;
        }
        double result = def;
        try {
            result = Double.parseDouble(str.toString());
        } catch (NumberFormatException e) {
            return def;
        }
        return result;
    }

    /**
     * 返回指定字符在传入字符串中出现数量
     *
     * @param inStr
     *            传入字符串
     * @param appearStr
     *            指定查找字符
     * @return
     */
    public static int getStringAppearNum(String inStr,String appearStr){
        int countNum=0;
        if(!inStr.equals("")){
            int inStrLength=inStr.length();
            String tmpStr=inStr.replaceAll(appearStr, "");
            countNum=inStrLength-tmpStr.length();
        }
        return countNum;
    }

    /**
     * 判断文件类型，供文件上传使用
     *
     * @param pInput 文件名
     * @return 0：未知 	1：语音	2：图片	3：文档		4：视频
     * @throws Exception
     */
    public static int fileType(String pInput){
        //文件名称为空的场合
        if(containEmpty(pInput)){
            //返回不合法
            return 0;
        }
        //获得文件后缀名
        String tmpName = pInput.substring(pInput.lastIndexOf(".")+1,pInput.length());
        //是否语音
        if(tmpName.equals("amr")){
            return 1;
        }

        //声明图片后缀名数组
        String imgeArray [] = {
                "bmp","dib","gif","jfif","jpe",
                "jpeg", "jpg","png","tif", "tiff","ico"
        };
        //是否图片
        for(int i = 0; i<imgeArray.length;i++){
            //判断单个类型文件的场合
            if(imgeArray[i].equals(tmpName.toLowerCase())){
                return 2;
            }
        }

        //声明视频后缀名数组
        String videoArray [] = {
                "avi","rmvb","3gp","mp4","mov",
                "rm","wmv","mpg","asf","mpeg"
        };
        //是否视频
        for(int j = 0; j<videoArray.length;j++){
            //判断单个类型文件的场合
            if(videoArray[j].equals(tmpName.toLowerCase())){
                return 4;
            }
        }

        //其他文件全部默认为文档
        return 3;
    }

    /**
     * 取得主域名
     * @param request
     * @return
     */
    public static String getDomainStr(HttpServletRequest request){
        String domain="";
        String[] strs=request.getServerName().split("\\.");
        if(strs.length<4){
            //循环域名
            for(int i=strs.length-1;i>strs.length-3;i--){
                domain="."+strs[i]+domain;
            }
        }
        return domain;
    }

    /**
     * 取得主域名
     * @param serverName
     * @return
     */
    public static String getDomainStr(String serverName){
        if (containEmpty(serverName)) {
            return "";
        }

        String domain="";
        String[] strs=serverName.split("\\.");
        if(strs.length<4){
            //循环域名
            for(int i=strs.length-1;i>strs.length-3;i--){
                domain="."+strs[i]+domain;
            }
        }
        return domain;
    }

    /**
     * 处理时间串《轨迹上传开始结束》得到hour minute  815  08 15
     * @param hour_minute_value
     * @return
     */
    public static List<String> getHoutMinute(int hour_minute_value){
        int clock_start_hour = (int)Math.floor(hour_minute_value/100);
        int clock_start_minute = hour_minute_value%100;
        String minuteStr = "";
        if(clock_start_minute < 10){
            minuteStr = "0" + clock_start_minute;
        }else{
            minuteStr = clock_start_minute + "";
        }
        List<String> hour_minute_list = new ArrayList<String>();
        hour_minute_list.add(String.valueOf(clock_start_hour));
        hour_minute_list.add(minuteStr);
        return hour_minute_list;
    }

    /**
     * 将ID字符串转成SET
     * @param idStr
     * 			ID字符串
     * @param separator
     * 			分隔符
     * @return
     */
    public static Set<Integer> transferStr2Set(String idStr, String separator){
        //返回值对象
        Set<Integer> retSet = new HashSet<Integer>();
        if(!StringUtil.containEmpty(idStr)){
            if(StringUtil.containEmpty(separator)){
                separator = ",";
            }

            String[] tempArr = idStr.split(separator);
            for(int i = 0;i<tempArr.length;i++){
                int temp = StringUtil.getInt((tempArr[i]),0);
                retSet.add(temp);
            }
        }

        return retSet;
    }


    /**
     * 将数组转成Collection
     * @param collection
     * 			ID字符串
     * @param tempArr
     * 			分隔符
     * @return
     */
    public static <T> void transferStr2Set(Collection<T> collection,T[] tempArr){
        //返回值对象
        if(collection != null){

            for(int i = 0;i<tempArr.length;i++){
                T temp = tempArr[i];
                collection.add(temp);
            }
        }
    }

    /**
     * 将集合转成字符串
     *
     * @param collection
     * 			集合
     * @param separator
     * 			分隔符
     * @return
     */
    public static <E> String transferColl2String(Collection<E> collection,String separator){
        StringBuilder builder = new StringBuilder("");
        if(collection != null && collection.size() > 0){
            for(E intStr:collection){
                builder.append(intStr.toString()).append(separator);
            }
        }
        if(builder.length() > 0 && !"".equals(separator)){
            return builder.substring(0, builder.length()-1).toString();
        }
        return builder.toString();
    }
    /**
     * 得到amr的时长
     *
     * @param file
     * @return
     * @throws IOException
     */


    /**
     * 字符解密
     * @param key
     * @return
     */
    public static String getURLDecoderOld(String key){
        try{
            return URLDecoder.decode(URLDecoder.decode(key));
        }catch (Exception e) {
            // TODO: handle exception
            return key;
        }
    }


    /**
     * 字符解密
     * @param key
     * @return
     */
    public static String getURLDecoder(String key){
        try{
            return URLDecoder.decode(URLDecoder.decode(key,"UTF-8"),"UTF-8");
        }catch (Exception e) {
            // TODO: handle exception
            return key;
        }
    }

    /**
     * 字符串转成List
     *
     * @param str
     * 			字符串
     * @param separtor
     * 			分割符
     * @param isDistinct
     * 			是否去重
     * @return
     */
    public static List stringToList(String str,String separtor,int type,boolean isDistinct){
        String [] strArr = str.split(separtor);

        List resultList = new ArrayList();
        Set resultSet = null;
        if(isDistinct){
            resultSet = new LinkedHashSet();
        }

        for(int i =0;i<strArr.length;i++){
            Object value = strArr[i].trim();
            switch(type){
                case 1:
                    value = StringUtil.getInt(String.valueOf(value), 0);
                    break;
                case 2:
                    value = StringUtil.getString(value);
                    break;
                default:
                    break;
            }

            if(isDistinct){
                resultSet.add(value);
            }else{
                resultList.add(value);
            }
        }

        if(isDistinct){
            resultList.addAll(resultSet);
        }

        return resultList;
    }

    /**
     * 删除Html标签
     * @param htmlStr
     * @return
     *
     */
    public static String delHTMLTag(String htmlStr) {

        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
        String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
        String regEx_space = "\\s*|\t|\r|\n";//定义空格回车换行符

        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); // 过滤script标签

        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); // 过滤style标签

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); // 过滤html标签

        Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
        Matcher m_space = p_space.matcher(htmlStr);
        htmlStr = m_space.replaceAll(""); // 过滤空格回车标签
        return htmlStr.trim(); // 返回文本字符串
    }

    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("-?[0-9]+.*[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if(!isNum.matches()){
            return false;
        }
        return true;
    }

    /**
     * 获取远程客户端ID
     *
     *
     *
     * @param request
     * @return
     */
    public static String getClientIP(HttpServletRequest request){
        //
        String ip=request.getHeader("x-forwarded-for");

        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("Proxy-Client-IP");
        }

        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("WL-Proxy-Client-IP");
        }

        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip=request.getHeader("X-Real-IP");
        }

        if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            ip=request.getRemoteAddr();
        }

        return ip;
    }

    public static boolean empty(Collection collection){
        if(collection == null || collection.isEmpty()){
            return true;
        }
        return false;
    }
}
